<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\model\Member;

use app\admin\model\User;
use app\admin\model\School;
use app\admin\model\Departments;
use app\admin\model\Clss;
use think\Db;

/**
 * 会员管理-服务类
 * @author 牧羊人
 * @since 2020/11/20
 * Class MemberService
 * @package app\admin\service
 */
class MemberService extends BaseService
{
    /**
     * 构造函数
     * @author 牧羊人
     * @since 2020/11/20
     * MemberService constructor.
     */
    public function __construct()
    {
        $this->model = new Member();
    }

    /**
     * 获取数据列表
     * @return array
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];

        // 学校
        $organization = getter($param, "organization");
        if ($organization) {
            $map[] = ['organization', '=', $organization];
        }

        // 院系
        $superior = getter($param, "superior");
        if ($superior) {
            $map[] = ['superior', '=', $superior];
        }

        // 年级
        $grade = getter($param, "grade");
        if ($grade) {
            $map[] = ['grade', '=', $grade];
        }

        // 专业
        $professional = getter($param, "professional");
        if ($professional) {
            $map[] = ['professional', '=', $professional];
        }

        // 班级
        $class = getter($param, "class");
        
		if ($class) {
			$map[] = ['class', '=', $class];
			// $str = '"'.$class.'"';
            // $map[] = ['features', 'like','%'.$str.'%'];
		}
        // 是否体育院系
        // $stype = getter($param, "stype");
        // if ($stype==1) {
            // // if ($class) {
                // // $map[] = ['class', '=', $class];
            // // }
        // }else{
            // if ($class) {
                // $str = '"'.$class.'"';
                // $map[] = ['features', 'like','%'.$str.'%'];
            // }
            
        // }

        // 性别
        $gender = getter($param, "gender");
        if ($gender) {
            $map[] = ['gender', '=', $gender];
        }

        $realname = getter($param, "realname");
        if ($realname) {
            $map[] = ['realname', 'like','%'.$realname.'%'];
        }

        $roll = getter($param, "roll");
        if ($roll) {
            $map[] = ['roll', 'like','%'.$roll.'%'];
        }

        $avatar = getter($param, "avatar");
        if ($avatar) {
            if ($avatar==1) {
                $map[] = ['avatar', '<>',''];
            }
            if ($avatar==2) {
                $map[] = ['avatar', '=',''];
            }
            
        }
        return parent::getList($map, "id asc"); // TODO: Change the autogenerated stub
    }

    /**
     * 获取用户信息
     * @param $userId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function getUserInfo($userId)
    {
        $user = new User();
        $userInfo = $user->getInfo($userId);
        if ($userInfo['id']==1) {
            return message("管理员不可使用", false);
        }
        $memberinfo = $this->model->where('username',$userInfo['username'])->find();
        // 返回参数
        $result = array();
        $result['id'] = $memberinfo['id'];
        $result['avatar'] = $memberinfo['avatar'];
        $result['username'] = $memberinfo['username'];
        $result['realname'] = $memberinfo['realname'];
        $result['nickname'] = $memberinfo['realname'];
        $result['gender'] = $memberinfo['gender'];
        $result['mobile'] = $memberinfo['mobile'];
        // $result['email'] = $memberinfo['email'];
        $result['roll'] = $memberinfo['roll'];
        $result['type'] = $memberinfo['type'];
        $result['features'] = $memberinfo['features'];
        $school = new School();
        $departments = new Departments();
        $class = new Clss();
        $result['school_name'] = $school->where('id',$memberinfo['organization'])->value('name');
        $result['superior_name'] = $departments->where('id',$memberinfo['superior'])->value('name');
        $result['class_name'] = $class->where('id',$memberinfo['class'])->value('name');
        $result['header'] = $class->where('id',$memberinfo['class'])->value('header');
        
        return message("操作成功", true, $result);
    }

    /**
     * 更新个人资料
     * @param $userId 用户ID
     * @return array
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     * @author 牧羊人
     * @since 2021/4/23
     */
    public function updateUserInfo($userId)
    {
        // 参数
        $param = request()->param();
        $loginUser = Db::table('think_user')->where('id',$userId)->find();
        $mem = Db::table('think_member')->where('username',$loginUser['username'])->find();
        // 个人信息
        $data = [
            'id' => $mem['id'],
            'realname' => $param['realname'],
            'nickname' => $param['nickname'],
            'gender' => $param['gender'],
            'mobile' => $param['mobile'],
            // 'email' => $param['email'],
            // 'intro' => $param['intro'],
        ];
        // 头像处理
        $avatar = isset($param['avatar']) ? $param['avatar'] : "";
        if (strpos($avatar, "data:image") !== false) {
            $expData = explode(';', $avatar);
            $fileInfo = explode('/', $expData[0]);
            $fileExt = $fileInfo[1] == 'jpeg' ? 'jpg' : $fileInfo[1];
            // 文件存储路径
            $filePath = create_image_path("user", $fileExt);

            // 获取图片流
            $item = explode(',', $avatar);
            file_put_contents(ATTACHMENT_PATH . $filePath, base64_decode($item[1]));

            $data['avatar'] = $filePath;
        } else {
            $data['avatar'] = str_replace(IMG_URL, "", $param['avatar']);
        }
        $result = $this->model->edit($data);
        if (!$result) {
            return message("更新资料信息失败", false);
        }
        return message("更新资料信息成功");
    }

    /**
     * 添加或编辑
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function edit()
    {
        // 请求参数
        $data = request()->param();
        $member = new Member();
        $md = $member->where('username',$data['username'])->value('id');
        if (isset($data['id'])&&!$data['id']) {
            if ($md) {
                return message('账户重复，请重新输入', false);
            }
        }
        
        // 头像处理
        $avatar = getter($data, 'avatar');
        $preg = "/^http(s)?:\\/\\/.+/";
        if (!preg_match($preg, $avatar)) {
            if (strpos($avatar, "temp")) {
                $data['avatar'] = save_image($avatar, 'member');
            }
        }
        

        if (isset($data['password'])&&$data['password']) {
            $data['password'] = get_password($data['password'] . $data['username']);
        }

        // 出生日期
        // if ($data['birthday']) {
        //     $data['birthday'] = strtotime($data['birthday']);
        // }

        // 城市数据处理
        // $city = $data['city'];
        // if (!empty($city)) {
        //     $data['province_code'] = $city[0];
        //     $data['city_code'] = $city[1];
        //     $data['district_code'] = $city[2];
        // } else {
        //     $data['province_code'] = 0;
        //     $data['city_code'] = 0;
        //     $data['district_code'] = 0;
        // }
        // unset($data['city']);
        Db::transaction(function () use ($data) {
            parent::edit($data);
            if (!empty($data['password'])) {
               (new User())->where('username', $data['roll'])->where('user_type', 2)->update(['password' => $data['password']]);
            }
        });
        return true;
    }

    /**
     * 获取学员列表
     * @return array
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getMemberList()
    {
        $param = request()->param();
        $where = [];
        $map1 = [];
        $where['mark'] = 1;
        $list = [];
        if (isset($param['class'])&& $param['class']>0) {
            $where['class'] = $param['class'];
        }
        $list = $this->model->where($where)->where($map1)->select()->toArray();
        //halt($this->model::getLastSql());
        $clist = [];
        $school = new School();
        $departments = new Departments();
        $class = new Clss();
        foreach ($list as $key => $value) {
            $clist[$key]['id'] = $value['id'];
            $clist[$key]['organization_name'] = $school->where('id',$value['organization'])->value('name');
            $clist[$key]['superior_name'] = $departments->where('id',$value['superior'])->value('name');
            $clist[$key]['class_name'] = $class->where('id',$value['class'])->value('name');
            $clist[$key]['name'] = $value['realname'];
            $clist[$key]['sex'] = $value['gender']==1?'男':'女';
        }
        return message("操作成功", true, $clist);
    }

}